from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from django.views import View
from django.http import HttpResponse
#导入原生sql模块
from django.db import connection
import json
from haochen.models import User
# Create your views here.

#对原生sql结果集美化方法
def dictfetchall(cursor):

    #获取游标描述
    desc = cursor.description

    return[
        dict(zip([col[0] for col in desc], row))

        for row in cursor.fetchall()
    ]


#用户登录
class UserAPI(APIView):

    def get(self,request):
        username = request.GET.get('username')

        users = User.objects.filter(username=username).first()

        if users:
            return Response({
                'code':200,
                'username':users.username,
                'uid':users.id
            })
        
        return Response({
            'code':400,
            'message':'用户名不存在',
        })


#订单
class OrderView(View):
    def get(self,request):
            
        #建立游标对象
        cursor = connection.cursor()

        #执行sql语句
        cursor.execute('SELECT `order`.id,`order`.time_s,`order`.order_number,`order`.s_name,`order`.price,goods.username,goods.num,goods.img FROM `order` ,goods WHERE `order`.goods_id =  goods.id')


        data = dictfetchall(cursor)
        return HttpResponse(json.dumps(data, ensure_ascii=False, indent=4, default=str),
                    content_type='application/json')





class CsAPI(APIView):

    def get(self,request):
        cs = request.GET.get('cs')

        return Response({
            'code':200,
            'cs':cs,
        })